package a07_二叉树;

/**
 * <p>
 * a15_最大二叉树
 * </p>
 * 遍历方式：必须是前序，中左右
 *
 * @author flyduck
 * @since 2024-09-24
 */
public class a19_最大二叉树复习1 {
    public static void main(String[] args) {
        int[] nums = new int[]{3,2,1,6,0,5};
        a19_最大二叉树复习1 test = new a19_最大二叉树复习1();
        TreeNode treeNode = test.constructMaximumBinaryTree(nums);
        System.out.println(treeNode);
    }

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        if (nums.length == 1) {
            return new TreeNode(nums[0]);
        }

        int maxIdx = 0;
        int maxValue = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > maxValue){
                maxIdx  = i;
                maxValue = nums[i];
            }
        }

        TreeNode treeNode = new TreeNode(maxValue);
        treeNode.left = constructMaximumBinaryTree(spiltArray(nums, 0, maxIdx - 1));
        treeNode.right = constructMaximumBinaryTree(spiltArray(nums, maxIdx + 1, nums.length - 1));
        return treeNode;
    }

    public int[] spiltArray(int[] oldArray,int leftIdx,int rightIdx){
        int[] newArray = new int[rightIdx - leftIdx + 1];
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = oldArray[leftIdx];
            leftIdx++;
        }
        return newArray;
    }
}
